package performance;//start extract InvokeBenchmark
import java.lang.reflect.*;

public class InvokeBenchmark {

    public static DoNothing target = new DoNothing();
    public static Class[] interfaces = { DoNothingInterface.class };

    public static Object newProxy( InvocationHandler obj ) {
	return Proxy.newProxyInstance( obj.getClass().getClassLoader(),
				       interfaces,
				       obj );
    }
    public static void main(String args[]) {
	int numberOfIterations = 5000000;
	DoNothingCaller caller = new DoNothingCaller();
	DoNothingInterface proxyForCaller 
	    = (DoNothingInterface)newProxy( caller );
	DoNothingInvoker invoker = new DoNothingInvoker();
	DoNothingInterface proxyForInvoker 
	    = (DoNothingInterface)newProxy( invoker );
	
	long time0 = System.currentTimeMillis();
	CallBenchmark.aDouble = 123456789.0;    
	for ( int j = 0; j < numberOfIterations; j++ )//#1 Direct call
	    InvokeBenchmark.target.doNothing();       //#1 to method
	long time1 = System.currentTimeMillis();      
	CallBenchmark.aDouble = 123456789.0; 
	for ( int j = 0; j < numberOfIterations; j++ )//#2 Call thru a proxy
	    proxyForCaller.doNothing( );              //#2 using a compiled call
	long time2 = System.currentTimeMillis();  
	CallBenchmark.aDouble = 123456789.0;   
	for ( int j = 0; j < numberOfIterations; j++ )//#3 Call thru a proxy
	    proxyForInvoker.doNothing( );             //#3 using Method.invoke
	long time3 = System.currentTimeMillis(); 
	
	double timeForProxyCall = (time2 - time1) - (time1 - time0);
	double timeForProxyCallPlusInvoke = (time3 - time2) - (time1 - time0);
//stop extract InvokeBenchmark
	System.out.println( "InvokeBenchmark: " + (time1 - time0) 
			    + " milliseconds for basic loop executing " 
			    + numberOfIterations + " iterations." );
//start extract InvokeBenchmark
	System.out.println( "InvokeBenchmark: " + timeForProxyCall 
			    + " milliseconds for " 
			    + numberOfIterations + " proxy calls." );
	System.out.println( "InvokeBenchmark: " + timeForProxyCallPlusInvoke 
			    + " milliseconds for " + numberOfIterations 
			    + " proxy calls using invoke." );
    }
}
//stop extract InvokeBenchmark
